﻿using System.Linq;
using Sausage.Common;
using Sausage.Data;

namespace Sausage.Domain
{
    public enum LoginResult
    {
        Ok = 0,
        UserDisabled = -1,
        UserPasswordNotMatch = -2,
        UserNotExist = -3,
        UserNotInRole = -4
    }

    public class LoginHelper
    {
        public static LoginResult LoginAdmin(string userName, string userPassword, out User user)
        {
            user = UserHelper.GetUserByName(userName);
            Role role = null;
            if (user != null)
            {
                role = RoleHelper.GetDefaultRoleByUser(user);
                if (PasswordHash.Compare(userPassword, user.Password))
                {
                    if (!user.IsEnabled)
                        return LoginResult.UserDisabled;
                    
                    var roleType = RoleHelper.GetRoleType(role);
                    if (roleType != RoleType.SectionAdmin &&
                          roleType != RoleType.DistrictAdmin)
                        return LoginResult.UserNotInRole;

                    return LoginResult.Ok;
                }
                return LoginResult.UserPasswordNotMatch;
            }
            return LoginResult.UserNotExist;
        }


        public static LoginResult LoginUser(string userName, string userPassword, out User user)
        {
            user = UserHelper.GetUserByName(userName);
            Role role = null;
            if(user != null)
            {
                role = RoleHelper.GetDefaultRoleByUser(user);
                if(PasswordHash.Compare(userPassword, user.Password))
                {
                    if(!user.IsEnabled)
                        return LoginResult.UserDisabled;

                    var roleType = RoleHelper.GetRoleType(role);
                    if (roleType != RoleType.MaintainUser &&
                          roleType != RoleType.ProjectUser)
                        return LoginResult.UserNotInRole;

                    return LoginResult.Ok;
                }
                return LoginResult.UserPasswordNotMatch;
            }
            return LoginResult.UserNotExist;
        }
    }
}
